package com.bafenyi.zh.bafenyilib;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat;
import com.bafenyi.zh.bafenyilib.activeWindow.BFYActiveWindow;
import com.bafenyi.zh.bafenyilib.activeWindow.BFYActivityWindowLifeCycle;
import com.bafenyi.zh.bafenyilib.activity.WebActivity;
import com.bafenyi.zh.bafenyilib.base.BFYBaseActivity;
import com.bafenyi.zh.bafenyilib.base.BFYBaseFragment;
import com.bafenyi.zh.bafenyilib.config.BFYConfig;
import com.bafenyi.zh.bafenyilib.request.BFYRequest;
import com.bafenyi.zh.bafenyilib.request.BFYRequestListener;
import com.bafenyi.zh.bafenyilib.util.Enum;
import com.bafenyi.zh.bafenyilib.util.PreferenceUtil;
import com.blankj.utilcode.util.ToastUtils;

import org.jetbrains.annotations.NotNull;
import java.text.SimpleDateFormat;
import java.util.Properties;

import pqsnevxshak.ejpsclxk.sKXILNcVyrQ;

public class BFYMethod {
    /**
     * 获取sdk版本号
     *
     * 请在gradle添加以下代码
     *
     *  defaultConfig添加
     *
     *  buildConfigField("String[]", "relyVersion", getRelyVersion())
     *
     *
     * gradle添加方法
        def getRelyVersion(){
          def config = file("../app/build.gradle")
            String contents = "new String[]{";
            config.eachLine { line ->
                if (line.contains('implementation')) {
                    contents = contents + "\"" + line + "\","
                }
            }
            return contents + "}"
        }
     *
     * */
    public static String getRelyVersion(String[] relyVersion){

        String bafenyiSdk_cn = "";
        String bafenyiAd_cn = "";
        String bafenyiPay_cn = "";
        String bafenyiLocalPay_cn = "";
        String bafenyiNews = "";

        for (String implementation : relyVersion) {
            if (implementation.contains("Android_BafenyiSdk_cn")) {
                bafenyiSdk_cn = implementation.replace("'" , "").split(":")[2];
                continue;
            }
            if (implementation.contains("Android_BafenyiAd_cn")) {
                bafenyiAd_cn = implementation.replace("'" , "").split(":")[2];
                continue;
            }
            if (implementation.contains("Android_BafenyiPay_cn")) {
                bafenyiPay_cn = implementation.replace("'" , "").split(":")[2];
                continue;
            }
            if (implementation.contains("Android_BafenyiLocalPay_cn")) {
                bafenyiLocalPay_cn = implementation.replace("'" , "").split(":")[2];
                continue;
            }
            if (implementation.contains("Android_BafenyiNews")) {
                bafenyiNews = implementation.replace("'" , "").split(":")[2];
            }
        }
        String result = "";
        if (!bafenyiSdk_cn.isEmpty()) {
            result = "Build" + bafenyiSdk_cn;
        }
        if (!bafenyiPay_cn.isEmpty()) {
            result = result + "-hp" + bafenyiPay_cn;
        }
        if (!bafenyiLocalPay_cn.isEmpty()) {
            result = result + "-lp" + bafenyiLocalPay_cn;
        }
        if (!bafenyiAd_cn.isEmpty()) {
            result = result + "-a" + bafenyiAd_cn;
        }
        if (!bafenyiNews.isEmpty()) {
            result = result + "-i" + bafenyiNews;
        }
        return result;
    }

    /**
     * 跳转应用市场评分（外部调用）
     * @param context 上下文
     * */
    public static void score(Context context){
        try {
            String brand = Build.BRAND;
            if("samsung".equals(brand)){
                Uri uri = Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + BFYConfig.getPkgName());
                Intent goToMarket = new Intent();
                goToMarket.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main");
                goToMarket.setData(uri);
                context.startActivity(goToMarket);
            }else {
                Uri uri = Uri.parse("market://details?id=" + BFYConfig.getPkgName());
                Intent intentScore = new Intent(Intent.ACTION_VIEW, uri);
                intentScore.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intentScore);
            }
        } catch (Exception e) {
            Toast.makeText(context, "未安装应用市场", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    /**
     * 下载apk（外部调用）
     * @param context 上下文
     * */
    public static void updateApk(Context context) {
        if (!BFYConfig.getUpdateApk().isEmpty()) {
            //通过浏览器去下载APK
            try {
                Uri uri = Uri.parse(BFYConfig.getUpdateApk());
                Intent viewIntent = new Intent("android.intent.action.VIEW", uri);
                context.startActivity(viewIntent);
            }catch (Exception e) {
                try {
                    String brand = Build.BRAND;
                    if("samsung".equals(brand)){
                        Uri uri = Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + BFYConfig.getPkgName());
                        Intent goToMarket = new Intent();
                        goToMarket.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main");
                        goToMarket.setData(uri);
                        context.startActivity(goToMarket);
                    }else {
                        Uri uri = Uri.parse("market://details?id=" + BFYConfig.getPkgName());
                        Intent intentScore = new Intent(Intent.ACTION_VIEW, uri);
                        intentScore.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intentScore);
                    }
                } catch (Exception es) {
                    Toast.makeText(context, "未安装应用市场", Toast.LENGTH_SHORT).show();
                    es.printStackTrace();
                }
            }
            return;
        }
        try {
            String brand = Build.BRAND;
            if("samsung".equals(brand)){
                Uri uri = Uri.parse("http://www.samsungapps.com/appquery/appDetail.as?appId=" + BFYConfig.getPkgName());
                Intent goToMarket = new Intent();
                goToMarket.setClassName("com.sec.android.app.samsungapps", "com.sec.android.app.samsungapps.Main");
                goToMarket.setData(uri);
                context.startActivity(goToMarket);
            }else {
                Uri uri = Uri.parse("market://details?id=" + BFYConfig.getPkgName());
                Intent intentScore = new Intent(Intent.ACTION_VIEW, uri);
                intentScore.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intentScore);
            }
        } catch (Exception e) {
            Toast.makeText(context, "未安装应用市场", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
    /**
     * 分享（外部调用）
     * @param context 上下文
     * */
    public static void share(@NotNull Context context){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "我正在使用" + BFYConfig.getAppName() + "，快来试试吧！" + BFYConfig.getMarketUrl());
        context.startActivity(Intent.createChooser(intent, "Share"));
    }
    /**
     * 是否展示通知（外部调用）
     * @param context 上下文
     * */
    public static boolean isShowNotification(Context context) {
        boolean b = NotificationManagerCompat.from(context).areNotificationsEnabled();
        if (b) {
            return false;
        }else {
            long firstSetNotificationDate = PreferenceUtil.getFirstSetNotificationDate();
            if (firstSetNotificationDate == 0 || PreferenceUtil.getTimeExpend(firstSetNotificationDate) >= 10) {
                PreferenceUtil.setFirstSetNotificationDate(System.currentTimeMillis());
                return true;
            }
            return false;
        }
    }
    /**
     * 获取"分享评论"弹窗展示（外部调用）
     * @param activity mainActivity
     * @param fragment homeFragment(必须继承于BFYBaseFragment)
     * @param activeWindowResult 监听回调
     * */
    public static void showScoreOrShare(AppCompatActivity activity , BFYBaseFragment fragment , BFYMethodListener.GetActiveWindowResult activeWindowResult) {
        BFYActivityWindowLifeCycle lifeCycle = new BFYActivityWindowLifeCycle(activity , activeWindowResult);
        if (fragment != null) {
            fragment.is_hidden(is_show -> {
                if (is_show) {
                    activeWindowResult.onResult(BFYActiveWindow.isShowScoreOrShare());
                    BFYMethod.updateParams("");
                }
            });
            fragment.getLifecycle().addObserver(lifeCycle);
        }else {
            activity.getLifecycle().addObserver(lifeCycle);
        }
    }
    /**
     * 获取"更新"弹窗机制（外部调用）
     * @param isMain 是否主页调用
     * @param isClick 是否主动点击调用
     * @param getUpdateResult 展示回调
     * */
    public static void getUpdateType(boolean isMain , boolean isClick , BFYMethodListener.GetUpdateResult getUpdateResult) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                @SuppressLint("SimpleDateFormat")
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                if (isUpdate()) {
                    if (isClick) {  //主动点击，一定是非强制弹窗
                        getUpdateResult.onResult(Enum.ShowUpdateType.ShowUpdateTypeUpdate);
                    }else {
                        if (BFYConfig.getNewForceUpdate().equals("on")) {  //如果打开了强制弹窗，必弹强制弹窗
                            getUpdateResult.onResult(Enum.ShowUpdateType.ShowUpdateTypeForceUpdate);
                        }else {  //非强制弹窗
                            if (isMain) { //首页非强制弹窗每10天弹一次
                                if (PreferenceUtil.getString("main_update_date" , "").equals("") ||
                                        PreferenceUtil.getGapCount(PreferenceUtil.getString("main_update_date" , "") , sdf.format(System.currentTimeMillis())) >= 10) {
                                    //弹出后保存当前时间
                                    PreferenceUtil.put("main_update_date", sdf.format(System.currentTimeMillis()));
                                    getUpdateResult.onResult(Enum.ShowUpdateType.ShowUpdateTypeUpdate);
                                }else { // 10天内
                                    getUpdateResult.onResult(Enum.ShowUpdateType.ShowUpdateTypeNone);
                                }
                            }else { //关于我们页面的弹窗每10天弹一次
                                if (PreferenceUtil.getString("update_date" , "").equals("") ||
                                        PreferenceUtil.getGapCount(PreferenceUtil.getString("update_date" , "") , sdf.format(System.currentTimeMillis())) >= 10) {
                                    //弹出后保存当前时间
                                    PreferenceUtil.put("update_date", sdf.format(System.currentTimeMillis()));
                                    getUpdateResult.onResult(Enum.ShowUpdateType.ShowUpdateTypeUpdate);
                                }else { // 10天内
                                    getUpdateResult.onResult(Enum.ShowUpdateType.ShowUpdateTypeNone);
                                }
                            }
                        }
                    }
                }else {
                    //假定更新完成更新完成，计时系统重置
                    PreferenceUtil.put("update_date", "");
                    //假定更新完成更新完成，计时系统重置
                    PreferenceUtil.put("main_update_date", "");
                    getUpdateResult.onResult(Enum.ShowUpdateType.ShowUpdateTypeNone);
                }
            }
        },1000);
    }
    /**
     * 是否展示更多应用（外部调用）
     * @param view 更多应用展示view
     * */
    public static void setShowMoreApp(View view){
        if (view != null) {
            newMoreAppView = view;
        }
        if (newMoreAppView != null) {
            if (!BFYMethod.isShowAd()) {
                newMoreAppView.setVisibility(View.GONE);
            }else {
                if (BFYConfig.getNewMoreApp().toLowerCase().contains("off")) {
                    newMoreAppView.setVisibility(View.GONE);
                }else {
                    newMoreAppView.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * 跳转链接（外部调用）
     * @param activity 上下文
     * @param urlType 链接类型
     */
    public static void openUrl(BFYBaseActivity activity, Enum.UrlType urlType){
        activity.permissionsLinsten = (requestCode, permissions, grantResults) -> {
            if (requestCode == 1314) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    String deviceId = Settings.System.getString(activity.getContentResolver(),Settings.Secure.ANDROID_ID);
                    String url = "https://platform.8fenyi.cn/h5-chat?appId=" + BFYConfig.getStaticticalAppid() + "&deviceId=" + deviceId+ "&lang=cn";
                    String title = "提点意见";

                    Intent intent = new Intent(activity, WebActivity.class);
                    intent.putExtra("url",url);
                    activity.startActivity(intent);
                }else {
                    ToastUtils.showShort("当前功能需要获取权限");
                }
            }
        };

        String url = "";
        if (urlType == Enum.UrlType.UrlTypeFeedBack) {  //feedback
            if (ContextCompat.checkSelfPermission(activity, feedbackPermissions[0]) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(activity, feedbackPermissions[1]) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity , feedbackPermissions,1314);
                return;
            }
            String deviceId = Settings.System.getString(activity.getContentResolver(),Settings.Secure.ANDROID_ID);
            url = "https://platform.8fenyi.cn/h5-chat?appId=" + BFYConfig.getStaticticalAppid() + "&deviceId=" + deviceId+ "&lang=cn";
        }else if (urlType == Enum.UrlType.UrlTypeMoreApp) { //更多应用
            url = "https://m.8fenyi.cn/index.html?language=cn&system=android&packages=" + BFYConfig.getPkgName();
        }else if (urlType == Enum.UrlType.UrlTypeUserAgreement) { //用户协议
            url = "https://h5.8fenyi.cn/privacy/service-protocol.html";
        }else if (urlType == Enum.UrlType.UrlTypePrivacy) { //隐私政策
            url = "https://h5.8fenyi.cn/privacy/index-cn.html?appId=" + BFYConfig.getStaticticalAppid();
        }
        Intent intent = new Intent(activity, WebActivity.class);
        intent.putExtra("url",url);
        activity.startActivity(intent);
    }

    /**是否申请过权限**/
    public static void splashReportStatistical(BFYBaseActivity activity , BFYMethodListener.AdCallBackForInit adCallBackForInit, BFYMethodListener.AdCallBackForSplash adCallBackForSplash){
        BFYConfig.adCallBackForInit = adCallBackForInit;
        BFYConfig.adCallBackForSplash = adCallBackForSplash;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (activity.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {//无权限访问
                activity.permissionsLinsten = (requestCode, permissions, grantResults) -> {
                    if (requestCode == 1315) {
                        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                            sKXILNcVyrQ.Jvglxk().WdsNvgw(activity,"1000&1310&zvv5qu0952gboj4nz6x");
                        }
                        new Handler().postDelayed(()-> BFYMethod.report(activity , "init"),1000);
                    }
                };
                ActivityCompat.requestPermissions(activity , new String[]{Manifest.permission.READ_PHONE_STATE},1315);
            }else {
                sKXILNcVyrQ.Jvglxk().WdsNvgw(activity,"1000&1310&zvv5qu0952gboj4nz6x");
                new Handler().postDelayed(()-> BFYMethod.report(activity , "init"),1000);
            }
        }else {
            sKXILNcVyrQ.Jvglxk().WdsNvgw(activity,"1000&1310&zvv5qu0952gboj4nz6x");
            new Handler().postDelayed(()-> BFYMethod.report(activity , "init"),1000);
        }
    }
    /**
     * 是否展示广告
     * @return 是否展示
     * */
    public static boolean isShowAd(){
        if (PreferenceUtil.getBoolean("isAudit" , BFYConfig.getIsAppMarket())) {
            return false;
        }
        return Integer.parseInt(BFYConfig.getAppVersionCode()) <= Integer.parseInt(BFYConfig.getUpdateVersion());
    }


    /*************************一下为内部调用****************************/


    /**
     * 上报统计(内部处理)
     * @param activity 上下文
     * */
    public static void report(Activity activity , String type) {
        int delay = 0;
        if (PreferenceUtil.getInt("report_num" , 0) == 0) {
            delay = 0;
        }else if (PreferenceUtil.getInt("report_num" , 0) == 1) {
            delay = 3000;
        }else if (PreferenceUtil.getInt("report_num" , 0) == 2) {
            delay = 3000;
        }else {
            PreferenceUtil.put("report_num" , 0);
            if (type.equals("init")) {
                updateParams(type);
            }
            BFYRequest.getMoreAppPic((isSuccess, picArr) -> {
            });
            return;
        }
        new Handler().postDelayed(() -> BFYRequest.getTimeStamp((is_success, time_stamp) -> {
            if (is_success) {
                BFYRequest.reportStatistical(activity, time_stamp, new BFYRequestListener.ReportStatisticalResult() {
                    @Override
                    public void onResult(boolean isSuccess) {
                        if (!isSuccess) {  //失败
                            PreferenceUtil.put("report_num" , PreferenceUtil.getInt("report_num" , 0) + 1);
                            Looper.prepare();
                            report(activity , type);
                            Looper.loop();
                        }else {
                            PreferenceUtil.put("report_num" , 0);
                            if (type.equals("init")) {
                                updateParams(type);
                            }
                            BFYRequest.getMoreAppPic((isSuccess1, picArr) -> {
                            });
                        }
                    }
                    @Override
                    public void onError() {
                        PreferenceUtil.put("report_num" , PreferenceUtil.getInt("report_num" , 0) + 1);
                        Looper.prepare();
                        report(activity , type);
                        Looper.loop();
                    }
                });
            }else {  //失败
                PreferenceUtil.put("report_num" , PreferenceUtil.getInt("report_num" , 0) + 1);
                Looper.prepare();
                report(activity , type);
                Looper.loop();

            }
        }), delay);
    }
    /**
     * 更新配置参数（内部处理）
     * */
    public static void updateParams(String type) {
        if (PreferenceUtil.getInt("updateParamsNum" , 0) >= 3) {
            PreferenceUtil.put("updateParamsNum" , 0);
            ToastUtils.showShort("网络异常，请检查网络连接是否通畅。");
            new Handler(Looper.getMainLooper()).post(()->{
                if (type.equals("init")) {
                    if (BFYConfig.adCallBackForInit != null) {
                        BFYConfig.adCallBackForInit.onSuccess(BFYConfig.getOtherParamsForKey("adJson" , ""));
                    }
                    if (BFYConfig.adCallBackForSplash != null) {
                        BFYConfig.adCallBackForSplash.onSuccess(BFYMethod.isShowAd() , BFYConfig.getAdServer() , BFYConfig.getOtherParamsForKey("adJson" , ""));
                    }
                }
            });
            return;
        }
        BFYRequest.getTimeStamp((is_success, time_stamp) -> {
            if (!is_success) {
                PreferenceUtil.put("updateParamsNum" , PreferenceUtil.getInt("updateParamsNum" , 0) + 1);
                updateParams(type);
                return;
            }
            BFYRequest.getParams(time_stamp , BFYConfig.getLastUpdateTime(), (isSuccess) -> {
                if (!isSuccess) {
                    PreferenceUtil.put("updateParamsNum" , PreferenceUtil.getInt("updateParamsNum" , 0) + 1);
                    updateParams(type);
                    return;
                }
                new Handler(Looper.getMainLooper()).post(() -> {
                    setShowMoreApp(null);
                    if (type.equals("init")) {
                        if (BFYConfig.adCallBackForInit != null) {
                            BFYConfig.adCallBackForInit.onSuccess(BFYConfig.getOtherParamsForKey("adJson" , ""));
                        }
                        if (BFYConfig.adCallBackForSplash != null) {
                            BFYConfig.adCallBackForSplash.onSuccess(BFYMethod.isShowAd() , BFYConfig.getAdServer() , BFYConfig.getOtherParamsForKey("adJson" , ""));
                        }
                    }
                });
                PreferenceUtil.put("updateParamsNum" , 0);
            });
        });
    }

    /**
     * 是否需要更新(内部处理)
     * @return 是否需要更新
     * */
    private static boolean isUpdate() {
        return Integer.parseInt(BFYConfig.getUpdateVersion()) > Integer.parseInt(BFYConfig.getAppVersionCode());
    }
    /**
     * feedback权限数组
     * */
    private static String[] feedbackPermissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
    };
    /**
     * 更多应用view*/
    @SuppressLint("StaticFieldLeak")
    private static View newMoreAppView;

}
